package com.fhx.core.base

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T> : RecyclerView.Adapter<BaseViewHolder>() {
    private val list = ArrayList<T>()
    var viewClickListener: ((T) -> Unit)? = null
    var itemClickListner: ((T) -> Unit)? = null
    var itemLongClickListener: ((T) -> Boolean)? = null

    open fun addData(data: List<T>) {
        if (data != null) {
            this.list.addAll(data)
            notifyDataSetChanged()
        }
    }


    open fun refreshData(data: List<T>) {
        if (data != null) {
            this.list.clear()
            this.list.addAll(data)
            notifyDataSetChanged()
        }
    }

    open fun clearData() {
        this.list.clear()
        notifyDataSetChanged()
    }

    open fun dataList(): ArrayList<T> {
        return list
    }

    override fun getItemCount(): Int = list.size

    final override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val holder = provideViewHolder(parent, viewType)!!
        setItemListener(holder, viewType)
        return holder
    }

    abstract fun provideViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder?

    protected open fun isClickEnabled(viewType: Int): Boolean {
        return true
    }

    protected open fun setItemListener(viewHolder: BaseViewHolder, viewType: Int) {
        if (!isClickEnabled(viewType)) return
        if (itemClickListner != null) {
            viewHolder.itemView.setOnClickListener {
                if (list.size > viewHolder.adapterPosition && viewHolder.adapterPosition >= 0) {
                    itemClickListner?.invoke(list[viewHolder.adapterPosition])
                }
            }
        }
        if (itemLongClickListener != null) {
            viewHolder.itemView.setOnLongClickListener {
                if (itemLongClickListener == null) {
                    false
                } else {
                    itemLongClickListener!!(list[viewHolder.adapterPosition])
                }
            }
        }
    }
}